<?php
namespace app\common\service;
use \app\common\model\LitestoreShop as LitestoreShopModel;
use Endroid\QrCode\QrCode;
use think\Loader;
use think\Validate;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/6
 * Time: 18:06
 */
class LitestoreShop extends Base {
    public function __construct()
    {
        parent::__construct();
       $LitestoreShopModel =  new LitestoreShopModel();
        $this->model = $LitestoreShopModel;
    }
    public function ByCategory($map=""){
       $data = $this->model->alias('a')->where($map)
           ->join('zm_litestore_tag_mid tm','tm.lid = a.id')
           ->join('zm_litestore_tag t','t.id = tm.tid')
           ->join('zm_litestore_shopcategory c','c.id = a.category_id')->group('a.id')->field('*')->select();
       foreach($data as $k=>$v){
           $v['distance'] = (double)getdistance(config('config.lng'),config('config.lng'),$v['longitude'],$v['latitude']);
        }
       return $data;
    }
    /**
     * 首页推荐
     */
    public function ShopByPosidList($map,$order,$page){
        $litestoreshop = \app\common\model\LitestoreShop::where($map)
            ->order($order)
            ->group('id')
            ->page($page)
            ->field('id,name,address,desc,info,longitude,latitude,average,shop_image');
        $data_new=$litestoreshop->with("getShopByPosidMid")->with("getShopByTag")->select();
        if(empty($data_new)) return [];
         $datas = collection($data_new)->toArray();
        foreach($datas as &$v){
            $v['distance'] = (double)getdistance(config('config.lng'),config('config.lng'),$v['longitude'],$v['latitude']);
            foreach($v["get_shop_by_posid_mid"] as &$vv){
                if($vv['posidcode']=='shop_index'){
                    $v['posidname']=$vv['posidname'];
                    $v['posidimage']=$vv['posidimage'];
                    $v['posid']=$vv['id'];
                }
            }
            foreach($v["get_shop_by_tag"] as &$vvv){
                    $v['tag_list'][]=[
                        'id'=>$vvv['id'],
                        'tagname'=>$vvv['tagname']
                    ];
            }
            unset($v['get_shop_by_tag']);
            unset($v['get_shop_by_posid_mid']);
        }
        return $datas;
    }
    /**
     * 商品+评论
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getComment($id,$uid){

       $LitestoreShop  = \app\common\model\LitestoreShop::get($id);
       if(empty($LitestoreShop)){
           return [];
       }
        $UserCollectShop = new \app\common\model\UserCollectShop();
       $data = collection( $LitestoreShop->where('id',$id)->field('id,name,address,desc,info,longitude,latitude,shop_image,average,user_id')->with('getShopByComment')->select())->toArray();
        foreach($data as &$v){
            if(!empty($v['longitude'])&&!empty($v['latitude'])){
                $v['distance'] = (double)getdistance(config('config.lng'),config('config.lng'),$v['longitude'],$v['latitude']);
            }else{
                $v['distance'] = 0;
            }

         $v['is_check']=$UserCollectShop->where(['shop_id'=>array('eq',$id),'user_id'=>array('eq',$uid)])->count();
          foreach ($v['get_shop_by_comment'] as &$vv){
              $vv['username'] = $vv['get_comment_by_user']['username'];
              $vv['avatar'] = $vv['get_comment_by_user']['avatar'];
              $vv['createtime'] = get_last_time($vv['createtime']);
              $vv['createtime'] = get_last_time($vv['createtime']);

              unset($vv['get_comment_by_user']);
          }
        }
            return $data;
    }

    /**
     * 生成二维码
     */
    public function createcode($shop_id){
        $playUrl=url('/index/user/merchant',array('shop_id'=>$shop_id),true,true);
        $file=$imagePath='codes/shopcode/'.$shop_id.'.png';
        if(file_exists($file)){
            return  $file;
        }else{
            $qrCode =  new QrCode();//创建生成二维码对象
            $qrCode->setText($playUrl)
                ->setSize(150)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                ->setBackgroundColor(array('r' =>225, 'g' => 225, 'b' => 225, 'a' => 0))
                ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG)
                ->save($file);
        }
        return $file;
    }

    /**
     * 商品列表
     */
    public function getList($map,$order,$limit,$page){
        $LitestoreShopModel = LitestoreShopModel::where($map)
            ->order($order)
            ->field('id,name,shop_image,longitude,latitude,category_id,average')
            ->page($page)
            ->limit($limit);
        $datas = collection($LitestoreShopModel->with("getShopByCategory")->with("getShopByTag")->select())->toArray();
        foreach($datas as &$v){
            $v['distance'] = (double)getdistance(config('config.lng'),config('config.lng'),$v['longitude'],$v['latitude']);
            $v['categorename'] = $v["get_shop_by_category"]["name"];
            foreach($v["get_shop_by_tag"] as &$vvv){
                $v['tag_list'][]=[
                    'id'=>$vvv['id'],
                    'tagname'=>$vvv['tagname']
                ];
            }
            unset($v['get_shop_by_tag']);
            unset($v['get_shop_by_posid_mid']);
            unset($v['get_shop_by_category']);
        }
        return $datas;
    }
    /**
     * 注册申请商家
     */
    public  function registerShop($map,$data,$save_where){
        $validate =  Loader::validate('LitestoreShop');
        if(!$validate->check($data)){
            $datas = json_encode((object)null);
            return ['code'=>3,'msg'=>$validate->getError(),'data'=>$datas];
        }
        $model = $this->model;
        if(empty($save_where)){
            $res = $model->where($map)->field('id,name,category_id,address,user_card_on,user_card_back,license,status')->find();
            if($res){
                return ['code'=>2,'msg'=>'已经申请过了','data'=>$res];
            }
            $data['status']=0;
            $data['createtime']=time();
            $data['updatetime']=time();
            $_datas = $model->insertGetId($data);
        }else{
            $data['status']=0;
            $data['createtime']=time();
            $data['updatetime']=time();

            $_datas = $model->save($data,['id'=>$data['id']]);
        }


        if($_datas){
            $data['id']=$_datas;
            return ['code'=>1,'msg'=>'提交成功','data'=>$data];
        }
    }

    /**
     * 获取开店的状态
     */
    public function litestore($uid){
        $model = $this->model;
        $map= ['user_id'=>$uid];
        $result = $model->where($map)->field('status')->find();
        return $result;
    }
}





